package cn.joybreeze.controller;


import cn.joybreeze.common.result.R;
import cn.joybreeze.common.vo.OptionsQueryVO;
import cn.joybreeze.model.OptionsDO;
import cn.joybreeze.model.QuestionDO;
import cn.joybreeze.service.OptionsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kjwaa
 * @since 2021-09-15
 */
@RestController
@RequestMapping("/options-do")
public class OptionsController {

    @Autowired
    OptionsService optionsService;

    /**
     * 增加选项记录
     * @param queryVO
     * @return
     */
    @PostMapping("/add")
    public R addOption(@RequestBody OptionsQueryVO queryVO){
        OptionsDO optionsDO = new OptionsDO();
        BeanUtils.copyProperties(queryVO, optionsDO);
        boolean isSuccess = optionsService.saveOrUpdate(optionsDO);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据选项id删除选项
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteOption(@PathVariable int id){
        boolean isSuccess = optionsService.removeById(id);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据问卷id删除对应的选项
     * @param questionnaireId
     * @return
     */
    @DeleteMapping("/deleteByQuestionnaireId/{questionnaireId}")
    public R deleteOptionsByQuestionnaireId(@PathVariable int questionnaireId){
        QueryWrapper<OptionsDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id", questionnaireId);
        boolean isSuccess = optionsService.remove(queryWrapper);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据问题id删除选项记录
     * @param questionId
     * @return
     */
    @DeleteMapping("/deleteByQuestionId/{questionId}")
    public R deleteOptionByQuestionId(@PathVariable int questionId){
        QueryWrapper<OptionsDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId);
        boolean isSuccess = optionsService.remove(queryWrapper);
        if(isSuccess) return R.ok();
        return R.error();
    }

    /**
     * 根据问卷id和问题id获取选项列表
     * @param questionId
     * @return
     */
    @GetMapping("/list/{questionnaireId}/{questionId}")
    public R getOptionsByQuestionId(@PathVariable int questionnaireId, @PathVariable int questionId){
        QueryWrapper<OptionsDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId);
        queryWrapper.eq("questionnaire_id", questionnaireId);
        List<OptionsDO> list = optionsService.list(queryWrapper);
        return R.ok(list);
    }




}
